import { Vector3, Matrix4 } from "../three.module.js";
import Geography from "../Geography.js";

//球体(用于等距圆柱贴图的球体)
export default class Earth {
    constructor(r = 0.1, widthSegments = 16, heightSegments = 16) {
        this.r = r;
        this.widthSegments = widthSegments;
        this.heightSegments = heightSegments;

        this.normals = [];//顶点法向
        this.vertices = [];//顶点信息
        this.elements = [];//默认的Elements
        this.uv = [];
        this.count = 0;

        this._init();
    }

    _init() {
        const { widthSegments, heightSegments, normals, vertices, elements, uv, r } = this;
        const [width, height] = [widthSegments + 1, heightSegments + 2];
        this.count = width * height;

        //加入顶点

        const perW = 360 / widthSegments;
        const perH = 180 / (heightSegments + 1);

        const uvW = 1 / widthSegments;
        const uvH = 1 / (heightSegments + 1);

        const geography = new Geography(r, 0, 0);

        const jd = -90 * Math.PI / 180;

        for (let i = 0; i < height; i++) {
            let phi = (90 - perH * i) * Math.PI / 180;
            for (let j = 0; j < width; j++) {
                let theta = (perW * j + 180) * Math.PI / 180;
                const posi = geography.getPosition(theta, phi);
                const posi1 = posi.applyMatrix4(new Matrix4().makeRotationY(jd));

                vertices.push(...posi1);
                normals.push(...posi1.normalize());
                uv.push(j * uvW, 1 - (i * uvH));

                if (i > 0 && j > 0) {
                    const lt = (i - 1) * width + (j - 1);
                    const rt = (i - 1) * width + j;
                    const lb = (i * width) + (j - 1);
                    const rb = (i * width) + j
                    elements.push(lt, lb, rb, lt, rb, rt);
                }

            }
        }
    }


}